<?php

/**
 * @Author: kendy
 * @Date:   2020-02-11 10:26:45
 * @Last Modified by:   jiayanting
 * @Last Modified time: 2020-02-24 16:41:10
 */ 
namespace app\api\controller;
use think\Db;
use think\Request; 
class Payments extends Nocommon
{
/**
 * [getFieldByType 根据类型获取字段]
 * @Author   kendy
 * @DateTime 2020-02-11T13:01:53+0800
 * @param    [type]                   $payType [支付类型 1酒店，2景点，3跟团]
 * @return   [type]                            []
 */
public function getFieldByType($orderType){  
      if($orderType==1){
      	 return  ['hotel_order','uid','hotel','hotel_id','hotel_id','hotel_name']; 
      }
      if($orderType==2){
         return  ['tour_order','user_id','tours','tour_id','tour_id','tour_name']; 
      }
      if($orderType==3){ 
        return   ['gtour_order','user_id','group_tour','id','gtour_id','gtour_title']; 
      } 
}




/**
 * [complatePay 完成支付订单]
 * @Author   kendy
 * @DateTime 2020-02-11T10:27:31+0800
 * @param    [type]                   $obj [支付成功返回对象]
 * @return   [type]                        [description]
 */
public function complatePay(){ 
	//$obj
		$tradeNo = 123528974;// $obj["trade_no"]; //支付宝交易号
		$orderId = 32;//$obj["out_trade_no"]; //商户订单号
		$userId = 1;//(int)$obj["user_id"];
		$payType = 1;//(int)$obj["pay_type"]; //支付类型1支付宝，2微信
		$payPrice = 250;//(float)$obj["total_amount"];
		$orderType = 3;//(int)$obj["order_type"]; //订单类型 订单类型 1酒店，2景点，3跟团
		$orderTable = $this->getFieldByType($orderType); 
		if($payType>0){
			$cnt = Db::name($orderTable[0])
						->where(['pay_type'=>$payType,$orderTable[1]=>$userId,"trade_no"=>$tradeNo,'order_id'=>$orderId])
						->count();
			if($cnt>0){ 
			 	$this->apiReturn('400','订单已支付',0);
			}
		}
		$priceField = 'total_price';
		if($orderType == 2){
            $priceField = 'order_price';
		}
		$where = [$orderTable[1]=>$userId,'order_id'=>$orderId,"order_status"=>0,"is_pay"=>2,$priceField=>[">",0]]; 
	   $totalPrice = Db::name($orderTable[0])->where($where)->value($priceField);    
		if($totalPrice>$payPrice){
			$this->apiReturn('400','支付金额不正确',0);
		} 
		Db::startTrans();
		try{
			$data = array(); 
			$data["is_pay"] = 1;
			$data["trade_no"] = $tradeNo;
			$data["pay_type"] = $payType;
			$data["order_status"] = 1;
			if($orderType == 1){
				$data["order_status"] = 6;
			}

			$rs =  Db::name($orderTable[0])->where($where)->update($data); 
            $orderInfo = Db::name($orderTable[0])
            ->alias("o") 
            ->join(''.$orderTable[2].' shop ','shop.'.$orderTable[3].'=o.'.$orderTable[4].'','inner')
            ->where(["o.order_id"=>$orderId])
            ->find();     
			if($payPrice>0 && false != $rs){
						$orderId = $orderInfo["order_id"];
						//新增订单日志
						$logOrder = [];
						$logOrder['order_id'] = $orderId;
						$logOrder['order_status'] = $data["order_status"];
						$logOrder['log_content'] = "订单已支付,下单成功";
						$logOrder['user_id'] = $userId; 
						$logOrder['create_time'] = time();
						$logOrder['order_type'] = $payType; 
						Db::name('log_orders')->insert($logOrder);
						//创建一条支付流水记录
		            	$lm = [];
						$lm['target_type'] = 0;
						$lm['target_id'] = $userId;
						$lm['data_id'] = $orderId;
						$lm['data_src'] = 1;
						$lm['remark'] = '交易订单【'.$orderInfo['order_sn'].'】支付¥'.$payPrice;
						$lm['money_type'] = 0;
						$lm['money'] = $payPrice;
						$lm['money_type'] = 0;
						$lm['pay_type'] = $payType;
						$lm['create_time'] = date('Y-m-d H:i:s');
						Db::name('log_moneys')->insert($lm);
						//增加未结算的订单佣金   
				          $commissionFee = 0; 
				          if($orderInfo['commission_rate']>0 && $orderType ==1){
				              $commissionFee = $orderInfo[$priceField]*$orderInfo['room_amount']*$orderInfo['commission_rate']/1000;
				           }else{ 
                             $commissionFee = $orderInfo[$priceField]*$orderInfo['commission_rate']/1000;
				           } 
                          
                        //未结算单的订单佣金 
                        if($orderType == 3){
                        	$teamInfo = Db::name("team")->where("team_id",$orderInfo['team_id'])->find();//->setInc('no_settled_order_fee',$commissionFee);
                        	Db::name("team")->where("team_id",$orderInfo['team_id'])->update(['no_settled_order_fee'=>$teamInfo['no_settled_order_fee']+$commissionFee]);
                        	$orderInfo['send_tel'] = $teamInfo['send_tel'];

                        }else{
                        	Db::name($orderTable[2])->where($orderTable[3],$orderInfo[$orderTable[3]])->setInc('no_settled_order_fee',$commissionFee);
                        }
						 
                       
						//发送一条商家信息 
						$fasong = [
			                '1' => $orderInfo[$orderTable[4]],
			                '2' => $orderInfo['order_sn']
			            ];  
					    sendJsmsMessage($orderInfo['send_tel'],174980, $fasong);


			}
			Db::commit(); 
			$this->apiReturn('200','支付成功',0);
		}catch (\Exception $e) {
			Db::rollback(); 
			$this->apiReturn('400','操作失败',$e->getMessage()); 
		}
	} 

}